'use strict';

module.exports = app => {
  class Conversation extends app.Service {
    async createConversationInfo(conversationId, sendUserId, content, contentType) { // 创建一个会话，并且跟工单和会话列表相关联。
      try {
        const conversationInfo = await app.model.ConversationInfo.create({ conversation_id: conversationId, send_user_id: sendUserId, content, content_type: contentType });
        return conversationInfo;
      } catch (e) {
        return null;
      }
    }

    async getConversationInfos(conversationId) { // 获取会话的详细信息。按创建时间排序
      try {
        const conversationInfos = await app.model.ConversationInfo.findAll({
          where: { conversation_id: conversationId },
          // order: [[ 'updatedAt', 'DESC' ]],
          attributes: [ 'content', 'conversation_id', [ 'created_at', 'send_time' ], [ 'id', 'info_id' ], [ 'content_type', 'send_type' ]],
          include: [{ // include关键字表示关联查询
            as: 'send_user',
            model: app.model.User, // 指定关联的model
          }],
        });
        return conversationInfos;
      } catch (e) {
        return null;
      }
    }

    async getAllConversationInfosWithStaff(userId) { // 获取所有该用户与客服的对话记录
      try {
        const conversationInfos = await app.model.ConversationInfo.findAll({
          attributes: [ 'content', 'conversation_id', [ 'created_at', 'send_time' ], [ 'id', 'info_id' ], [ 'content_type', 'send_type' ]],
          include: [{
            model: app.model.Conversation,
            attributes: [],
            where: { user_id: userId },
          }, {
            as: 'send_user',
            model: app.model.User, // 指定关联的model
          }],
        });
        return conversationInfos;
      } catch (e) {
        return null;
      }
    }

    async evaluate(infoId, score) {
      try {
        const conversationInfos = await app.model.ConversationInfo.update({ content: score }, { where: { id: infoId } });
        return conversationInfos;
      } catch (e) {
        return null;
      }
    }
  }
  return Conversation;
};
